package com.zhenyi.liuxue.admin;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.liuxue.common.model.LxCompany;
import com.liuxue.common.model.LxUser;
import com.utils.PathUtils;
import com.zhenyi.liuxue.core.TemplateUtils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

public class UserController extends AdminController {

	public void list() {
		String keyword = getPara("keyword");
		// String location = getPara("location");
		String province = getPara("province");
		String city = getPara("city");
		Long companyId = getParaToLong("companyId");
		Integer status = getParaToInt("status");
		Kv kv = Kv.create();
		if (StrKit.notBlank(keyword)) {
			kv.set("keyword", keyword);
			setAttr("keyword", keyword);
		}
		// if (StrKit.notBlank(location)) {
		// kv.set("location", location);
		// setAttr("location", location);
		// }
		if (StrKit.notBlank(province)) {
			kv.set("province", province);
			setAttr("province", province);
		}
		if (StrKit.notBlank(city)) {
			kv.set("city", city);
			setAttr("city", city);
		}
		if (companyId != null) {
			kv.set("companyId", companyId);
			setAttr("companyId", companyId);
		}
		if (status != null) {
			kv.set("status", status);
			setAttr("status", status);
		}
		if (getParaToInt("dl", 0).equals(1)) {
			downloadUserList(kv);
			return;
		}
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXAdminFindUser", kv);
		Page<LxUser> pages = LxUser.dao.paginate(getPage(), getPageSize(), sqlPara);
		SqlPara sqlPara2 = Db.use("liuxue").getSqlPara("LXFindCompanies");
		List<LxCompany> companies = LxCompany.dao.find(sqlPara2);

		setRainbow(pages);
		setItems(JsonKit.toJson(pages.getList()));
		setAttr("companies", JsonKit.toJson(companies));
		render("/lx/admin/user/index.html");
	}

	public void info() {
		setReferer();
		Long userId = getParaToLong("userId");
		if (userId != null) {
			LxUser info = LxUser.dao.findById(userId);
			if (info == null) {
				renderFailure(404, "info not found");
				return;
			}
			Kv kv = Kv.create();
			kv.set("userId", userId);
			SqlPara sp = Db.use("liuxue").getSqlPara("LXAdminFindUserCert", kv);
			List<Record> certs = Db.use("liuxue").find(sp);
			info.put("certs", certs);

			setInfoItem(JsonKit.toJson(info));
		}
		render("/lx/admin/user/info.html");
	}

	public void submit() {
		Long id = getParaToLong("id");
		String name = getPara("name");
		String firstName = getPara("firstName");
		String lastName = getPara("lastName");
		String englishName = getPara("englishName");
		Integer sex = getParaToInt("sex");
		String account = getPara("account");
		String password = getPara("password");
		String email = getPara("email");
		String card = getPara("card");
		String country = getPara("country");

		Integer status = getParaToInt("status");
		String content = getPara("content");

		LxUser info = null;
		if (id == null) {
			// info = new LxUser();
			// info.save();
			renderFailure(500, "id is null");
			return;
		} else {
			info = LxUser.dao.findById(id);
			if (info == null) {
				renderFailure(404, "user not found");
				return;
			}
		}
		info.setName(name);
		info.setFirstName(firstName);
		info.setLastName(lastName);
		info.setEnglishName(englishName);
		info.setSex(sex);
		info.setAccount(account);
		info.setPassword(password);
		info.setEmail(email);
		info.setCard(card);
		info.setCountry(country);

		Integer oldStatus = info.getStatus();
		info.setStatus(status);
		info.setContent(content);
		boolean flag = info.update();

		if (flag && !status.equals(oldStatus) && StrKit.notBlank(info.getOpenId())) {
			TemplateUtils templateUtils = new TemplateUtils();
			if (status.equals(2)) { // 审核通过
				templateUtils.sendVerifyPassed(info.getOpenId(), info.getFormId(), info.getName(),
						new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
			} else if (status.equals(3)) { // 审核不通过
				templateUtils.sendVeirfyFailed(info.getOpenId(), info.getFormId(), info.getName(), info.getContent(),
						new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
			}
		}

		renderFlag(flag);
	}

	public void delete() {
		Long userId = getParaToLong("userId");
		if (userId == null) {
			renderFailure(500, "id is null");
			return;
		}
		LxUser info = LxUser.dao.findById(userId);
		if (info == null) {
			renderFailure(404, "Not found");
			return;
		}
		// renderFlag(info.delete());
		info.setFlag(1);
		renderFlag(info.update());
	}

	private void downloadUserList(Kv kv) {
		SqlPara sqlPara;
		sqlPara = Db.use("liuxue").getSqlPara("LXAdminFindUser", kv);
		List<LxUser> items = LxUser.dao.find(sqlPara);
		ArrayList<List<String>> arrayList = new ArrayList<>();
		List<String> title = CollUtil.newArrayList("姓名", "英文名", "姓（拼音）", "名（拼音）", "性别", "省份", "城市", "公司", "擅长国家",
				"职能类别", "服务起始年月", "积分", "账号"/* , "密码" */);
		arrayList.add(title);
		for (LxUser info : items) {
			String name = info.getName();
			String englishName = info.getEnglishName();
			String lastName = info.getLastName();
			String firstName = info.getFirstName();
			Integer sexValue = info.getSex();
			String sex = "";
			if (sexValue != null) {
				sex = sexValue == 0 ? "男" : "女";
			}
			String province = info.getProvince();
			String city = info.getCity();
			String companyName = info.get("companyName");
			String country = info.getCountry();
			String department = info.getDepartment();
			String startDate = info.getStartDate();
			String point = info.getPoint().toString();
			String account = info.getAccount();
			// String password = info.getPassword();

			List<String> row = CollUtil.newArrayList(name, englishName, lastName, firstName, sex, province, city,
					companyName, country, department, startDate, point, account/* , password */);
			arrayList.add(row);
		}
		String now = DateUtil.now();
		now = now.replace("-", "");
		now = now.replace(":", "");
		now = now.replace(" ", "");
		String name = "用户列表-" + now + ".xlsx";
		String path = PathUtils.getFile("lx", "temp", "excel", name);
		ExcelWriter writer = ExcelUtil.getWriter(path);
		writer.write(arrayList);
		writer.close();
		File file = new File(path);
		renderFile(file);
	}

	public void verify() {
		Long userId = getParaToLong("userId");
		Integer status = getParaToInt("status");
		String content = getPara("content");
		if (userId == null || status == null) {
			renderFailure(500, "invalid params");
			return;
		}
		LxUser user = LxUser.dao.findById(userId);
		if (user == null) {
			renderFailure(404, "user not found");
			return;
		}
		user.setStatus(status);
		user.setContent(content);
		renderFlag(user.update());
	}

}
